package com.wisedu.mobile.auth.service.impl.v1.db;

import com.github.threefish.spring.sqltpl.annotation.SqlXml;
import com.wisedu.mobile.common.BaseServiceImpl;
import com.wisedu.mobile.common.constant.RedisConstants;
import com.wisedu.mobile.common.domain.SysMenu;
import com.wisedu.mobile.common.service.ISysMenuService;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.util.cri.Exps;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: hj
 * @Date: 2020/3/17 上午11:01
 */
@Service
@SqlXml
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenu> implements ISysMenuService {

    @Override
    @Cacheable(value = RedisConstants.LIMIT_MENU_KEY ,key = "methodName")
    public Map<String,SysMenu> selectLimiterMenu() {
        List<SysMenu> menus = query(Cnd.where(Exps.isNull("timeUnit").setNot(true)));
        return Lang.collection2map(ConcurrentHashMap.class,menus,"url");
    }

    @Override
    public List<Record> selectMenuByRole(String roleid) {
        Map param = new HashMap();
        param.put("roleid",roleid);
        return list("selectMenuByRole",null,param);
    }

    @Override
    @Cacheable(value = RedisConstants.K_MENU_KEY ,key = "methodName")
    public Map<String,SysMenu> select2kMenu() {
        List<SysMenu> menus = query(Cnd.where(Exps.isNull("enhanceUrl").setNot(true)));
        return Lang.collection2map(ConcurrentHashMap.class,menus,"url");
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        Map<String,SysMenu> sysMenus = new HashMap<>();
        for(SysMenu menu:menus){
            if(Strings.isEmpty(menu.getParentId())){
                if(sysMenus.get(menu.getId())!=null){
                    menu.setChildren(sysMenus.get(menu.getId()).getChildren());
                }
                sysMenus.put(menu.getId(),menu);
            }else{
                if(sysMenus.get(menu.getParentId())!=null){
                    sysMenus.get(menu.getParentId()).getChildren().add(menu);
                }else {
                    SysMenu m = new SysMenu();
                    m.getChildren().add(menu);
                    sysMenus.put(menu.getParentId(),m);
                }
            }
        }
        return Lang.collection2list(sysMenus.values());
    }
}
